import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Form, Input, Button, DatePicker, Radio, Switch, message, Space, Spin } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { contestService } from '@/services/contestService';
import { Contest} from '@/types/contest';
import styles from './Create.module.css';
import dayjs from 'dayjs';
import MDEditor from '@/components/MDEditor';

const { RangePicker } = DatePicker;

const ContestEdit: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [initializing, setInitializing] = useState(true);

  useEffect(() => {
    if (id) {
      fetchContest();
    }
  }, [id]);

  const fetchContest = async () => {
    try {
      setInitializing(true);
      const response = await contestService.getContest(Number(id));
      const contest = response.data.data;
      
      form.setFieldsValue({
        title: contest.title,
        description: contest.description,
        time: [dayjs(contest.start_time), dayjs(contest.end_time)],
        rule_type: contest.rule_type,
        contest_type: contest.contest_type,
        password: contest.password,
        real_time_rank: contest.real_time_rank,
        visible: contest.visible,
        allowed_ip_ranges: contest.allowed_ip_ranges?.join('\n') || ''
      });
    } catch (error) {
      message.error('获取比赛详情失败');
      navigate('/contest/list');
    } finally {
      setInitializing(false);
    }
  };

  const handleSubmit = async (values: any) => {
    if (!id) return;
    
    try {
      setLoading(true);
      
      const [startTime, endTime] = values.time;
      
      const contestData: Partial<Contest> = {
        title: values.title,
        description: values.description,
        start_time: startTime.toISOString(),
        end_time: endTime.toISOString(),
        rule_type: values.rule_type,
        password: values.contest_type === '1' ? values.password : undefined,
        real_time_rank: values.real_time_rank,
        visible: values.visible,
        contest_type: values.contest_type,
        allowed_ip_ranges: values.allowed_ip_ranges?.split('\n').filter(Boolean) || []
      };
      
      await contestService.updateContest(Number(id), contestData);
      message.success('比赛更新成功');
      navigate(`/contest/${id}`);
    } catch (error) {
      message.error('比赛更新失败');
    } finally {
      setLoading(false);
    }
  };

  if (initializing) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <Button 
          icon={<ArrowLeftOutlined />} 
          onClick={() => navigate(`/contest/${id}`)}
        >
          返回详情
        </Button>
      </div>

      <Card title="编辑比赛">
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="title"
            label="比赛标题"
            rules={[{ required: true, message: '请输入比赛标题' }]}
          >
            <Input placeholder="请输入比赛标题" />
          </Form.Item>

          <Form.Item
            name="time"
            label="比赛时间"
            rules={[{ required: true, message: '请选择比赛时间' }]}
          >
            <RangePicker 
              showTime 
              format="YYYY-MM-DD HH:mm:ss" 
              style={{ width: '100%' }}
            />
          </Form.Item>

          <Form.Item
            name="rule_type"
            label="规则类型"
            rules={[{ required: true, message: '请选择规则类型' }]}
          >
            <Radio.Group>
              <Radio value="ACM">ACM</Radio>
              <Radio value="OI">OI</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="contest_type"
            label="比赛类型"
            rules={[{ required: true, message: '请选择比赛类型' }]}
          >
            <Radio.Group>
              <Radio value="0">公开比赛</Radio>
              <Radio value="1">密码保护</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item
            name="password"
            label="比赛密码"
            rules={[
              ({ getFieldValue }) => ({
                validator(_, value) {
                  if (getFieldValue('contest_type') === '1' && !value) {
                    return Promise.reject(new Error('请输入比赛密码'));
                  }
                  return Promise.resolve();
                },
              }),
            ]}
            dependencies={['contest_type']}
          >
            <Input.Password placeholder="请输入比赛密码" />
          </Form.Item>

          <Form.Item
            name="real_time_rank"
            label="实时排名"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="visible"
            label="是否公开"
            valuePropName="checked"
          >
            <Switch />
          </Form.Item>

          <Form.Item
            name="allowed_ip_ranges"
            label="允许的IP范围"
            extra="每行一个IP范围，例如：192.168.1.1/24"
          >
            <Input.TextArea rows={4} placeholder="每行一个IP范围" />
          </Form.Item>

          <Form.Item
            name="description"
            label="比赛描述"
          >
            <MDEditor />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={loading}>
                更新比赛
              </Button>
              <Button onClick={() => navigate(`/contest/${id}`)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default ContestEdit; 